import Vue from 'vue'
import axios from 'axios'
import Qs from 'qs'
import { Message } from 'element-ui'
import store from '@/store'
import { getHuocmsToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import func from '@/utils/func'

// create an axios instance
const $axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 测试地址
  timeout: 50000 // request timeout
})

Vue.prototype.$axios = axios // 并发请求
// request interceptor
$axios.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getHuocmsToken()
      // config.headers['Authorization'] = getHuocmsToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
$axios.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case 403:
        if (func.TokenInvalidFlag == 0) {
          Message.error('登录已过期，请重新登录')
        }
        func.TokenInvalidFlag = 1
        resetRouter()
        removeToken()
        router.push({
          path: '/login',
          query: {
            redirect: '/'
          }
        })
        break
      default:
        if (response.data.code != 0 && response.data.code != -200) {
          Message.error(response.data.msg)
        }
        break
    }
    const code = response.status
    if ((code >= 200 && code < 300) || code === 304) {
      return Promise.resolve(response.data)
    } else {
      // 复位token无效标记
      func.TokenInvalidFlag = 0
      return Promise.reject(response)
    }
  },
  error => {
    console.log(error, '请求失败')
    if (error.response) {
      // switch (error.response.status) {
      //
      //   case 403:
      //     // 返回401 清除token信息并跳转到登陆页面
      //     store.commit('DEL_TOKEN')
      //     router.replace({
      //       path: '/login',
      //       query: {
      //         redirect: router.currentRoute.fullPath
      //       }
      //     })
      //     break
      //   case 404:
      //     Message.error('网络请求不存在')
      //     break
      //   default:
      //     Message.error(error.response.data.message)
      // }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes('timeout')) {
        Message.error('请求超时！请检查网络是否正常')
      } else {
        Message.error('请求失败，请检查网络是否已连接')
      }
    }
    return Promise.reject(error)
  }
)

export default {
  post(url, data, timeout = 60000) {
    return $axios({
      method: 'post',
      url,
      timeout: timeout,
      data: Qs.stringify(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  get(url, params) {
    return $axios({
      method: 'get',
      url,
      params
    })
  },
  // 上传图片 取消qs
  updata(url, data) {
    return $axios({
      method: 'post',
      url,
      data,
      timeout: 30000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  // 分片式上传
  chunkUpload(url, data) {
    return $axios({
      method: 'post',
      url,
      data,
      timeout: 60000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  }
}
